<template>
  <div>
    <h1 class="text-2xl font-bold mb-6">个人信息</h1>

    <a-row :gutter="24">
      <!-- 左侧：头像和基本信息 -->
      <a-col :span="8">
        <a-card class="text-center">
          <a-avatar :size="120" class="mb-4">
            {{ userInfo.username?.[0]?.toUpperCase() }}
          </a-avatar>
          <h2 class="text-xl font-bold mb-2">{{ userInfo.realName || userInfo.username }}</h2>
          <p class="text-gray-500">{{ userInfo.role || '管理员' }}</p>
          <a-button type="primary" class="mt-4" @click="showEditModalHandler">
            编辑资料
          </a-button>
        </a-card>
      </a-col>

      <!-- 右侧：详细信息 -->
      <a-col :span="16">
        <a-card>
          <template #title>基本信息</template>
          <a-descriptions :column="1">
            <a-descriptions-item label="用户名">
              {{ userInfo.username }}
            </a-descriptions-item>
            <a-descriptions-item label="真实姓名">
              {{ userInfo.realName || '未设置' }}
            </a-descriptions-item>
            <a-descriptions-item label="角色">
              {{ userInfo.role || '管理员' }}
            </a-descriptions-item>
            <a-descriptions-item label="邮箱">
              <div class="flex items-center justify-between">
                <span>{{ userInfo.email || '未设置' }}</span>
                <a-button
                  v-if="!userInfo.email"
                  type="primary"
                  size="small"
                  @click="showEmailVerifyModal = true"
                >
                  认证邮箱
                </a-button>
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="手机号">
              <div class="flex items-center justify-between">
                <span>{{ userInfo.phone || '未设置' }}</span>
                <a-button
                  v-if="!userInfo.phone"
                  type="primary"
                  size="small"
                  @click="showPhoneVerifyModal = true"
                >
                  认证手机号
                </a-button>
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="最后登录时间">
              {{ userInfo.lastLoginTime || '未知' }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <a-card class="mt-4">
          <template #title>认证状态</template>
          <a-descriptions :column="1">
            <a-descriptions-item label="手机号认证">
              <div class="flex items-center justify-between">
                <span>
                  <a-tag v-if="userInfo.phone" color="success">已认证</a-tag>
                  <a-tag v-else color="warning">未认证</a-tag>
                </span>
                <a-button
                  v-if="!userInfo.phone"
                  type="primary"
                  size="small"
                  @click="showPhoneVerifyModal = true"
                >
                  立即认证
                </a-button>
                <a-button
                  v-else
                  type="primary"
                  size="small"
                  @click="showPhoneVerifyModal = true"
                >
                  重新认证
                </a-button>
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="邮箱认证">
              <div class="flex items-center justify-between">
                <span>
                  <a-tag v-if="userInfo.email" color="success">已认证</a-tag>
                  <a-tag v-else color="warning">未认证</a-tag>
                </span>
                <a-button
                  v-if="!userInfo.email"
                  type="primary"
                  size="small"
                  @click="showEmailVerifyModal = true"
                >
                  立即认证
                </a-button>
                <a-button
                  v-else
                  type="primary"
                  size="small"
                  @click="showEmailVerifyModal = true"
                >
                  重新认证
                </a-button>
              </div>
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <a-card class="mt-4">
          <template #title>修改密码</template>
          <a-form
            :model="passwordForm"
            @finish="handlePasswordChange"
            layout="vertical"
          >
            <a-form-item
              label="当前密码"
              name="oldPassword"
              :rules="[{ required: true, message: '请输入当前密码' }]"
            >
              <a-input-password v-model:value="passwordForm.oldPassword" />
            </a-form-item>
            <a-form-item
              label="新密码"
              name="newPassword"
              :rules="[{ required: true, message: '请输入新密码' }]"
            >
              <a-input-password v-model:value="passwordForm.newPassword" />
            </a-form-item>
            <a-form-item
              label="确认新密码"
              name="confirmPassword"
              :rules="[
                { required: true, message: '请确认新密码' },
                { validator: validateConfirmPassword }
              ]"
            >
              <a-input-password v-model:value="passwordForm.confirmPassword" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit">
                修改密码
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>

    <!-- 编辑资料弹窗 -->
    <a-modal
      v-model:open="showEditModal"
      title="编辑个人信息"
      @ok="handleEdit"
      :confirmLoading="editLoading"
    >
      <a-form
        :model="editForm"
        layout="vertical"
      >
        <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="editForm.username" />
        </a-form-item>
        <a-form-item
          label="真实姓名"
          name="realName"
        >
          <a-input v-model:value="editForm.realName" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 手机号认证弹窗 -->
    <a-modal
      v-model:open="showPhoneVerifyModal"
      title="手机号认证"
      @ok="handlePhoneVerify"
      :confirmLoading="phoneVerifyLoading"
    >
      <a-form
        :model="phoneVerifyForm"
        layout="vertical"
      >
        <a-form-item
          label="手机号"
          name="phone"
          :rules="[
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
          ]"
        >
          <a-input v-model:value="phoneVerifyForm.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item
          label="验证码"
          name="code"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <div class="flex">
            <a-input v-model:value="phoneVerifyForm.code" placeholder="请输入验证码" />
            <a-button
              :disabled="phoneCodeSending || phoneCountdown > 0"
              @click="sendPhoneCode"
              class="ml-2"
            >
              {{ phoneCountdown > 0 ? `${phoneCountdown}秒后重新获取` : '获取验证码' }}
            </a-button>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 邮箱认证弹窗 -->
    <a-modal
      v-model:open="showEmailVerifyModal"
      title="邮箱认证"
      @ok="handleEmailVerify"
      :confirmLoading="emailVerifyLoading"
    >
      <a-form
        :model="emailVerifyForm"
        layout="vertical"
      >
        <a-form-item
          label="邮箱"
          name="email"
          :rules="[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入正确的邮箱格式' }
          ]"
        >
          <a-input v-model:value="emailVerifyForm.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item
          label="验证码"
          name="code"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <div class="flex">
            <a-input v-model:value="emailVerifyForm.code" placeholder="请输入验证码" />
            <a-button
              :disabled="emailCodeSending || emailCountdown > 0"
              @click="sendEmailCode"
              class="ml-2"
            >
              {{ emailCountdown > 0 ? `${emailCountdown}秒后重新获取` : '获取验证码' }}
            </a-button>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { useUserStore } from '@/stores/user'
import { anyPost } from '@/network'

const userStore = useUserStore()

// 用户信息计算属性
const userInfo = computed(() => {
  const info = userStore.userInfo || {}
  return {
    username: info.username || '',
    realName: info.realName || '',
    email: info.email || '',
    phone: info.phone || '',
    role: '管理员', // 可以根据权限或角色信息动态设置
    lastLoginTime: '未知' // 可以从后端获取
  }
})

// 编辑资料相关
const showEditModal = ref(false)
const editLoading = ref(false)
const editForm = reactive({
  username: '',
  realName: '',
})

// 修改密码相关
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 手机号认证相关
const showPhoneVerifyModal = ref(false)
const phoneVerifyLoading = ref(false)
const phoneCodeSending = ref(false)
const phoneCountdown = ref(0)
const phoneVerifyForm = reactive({
  phone: '',
  code: '',
})

// 邮箱认证相关
const showEmailVerifyModal = ref(false)
const emailVerifyLoading = ref(false)
const emailCodeSending = ref(false)
const emailCountdown = ref(0)
const emailVerifyForm = reactive({
  email: '',
  code: '',
})

// 验证确认密码
const validateConfirmPassword = async (_rule: Rule, value: string) => {
  if (value !== passwordForm.newPassword) {
    throw new Error('两次输入的密码不一致')
  }
}

// 初始化编辑表单
const initEditForm = () => {
  const info = userStore.userInfo || {}
  editForm.username = info.username || ''
  editForm.realName = info.realName || ''
}

// 处理编辑资料提交
const handleEdit = async () => {
  try {
    editLoading.value = true

    const response = await anyPost('/api/auth/update-profile', {
      username: editForm.username,
      realName: editForm.realName,
    })

    if (response.success) {
      // 更新本地用户信息
      await userStore.fetchUserInfo()
      message.success('修改成功')
      showEditModal.value = false
    } else {
      message.error(response.message || '修改失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    message.error('修改失败，请稍后重试')
  } finally {
    editLoading.value = false
  }
}

// 处理修改密码
const handlePasswordChange = async () => {
  try {
    const response = await anyPost('/api/auth/change-password', {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })

    if (response.success) {
      message.success('密码修改成功')
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      message.error(response.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    message.error('密码修改失败，请稍后重试')
  }
}

// 发送手机验证码
const sendPhoneCode = async () => {
  if (!phoneVerifyForm.phone) {
    message.error('请先输入手机号')
    return
  }

  if (!/^1[3-9]\d{9}$/.test(phoneVerifyForm.phone)) {
    message.error('请输入正确的手机号')
    return
  }

  try {
    phoneCodeSending.value = true

    const response = await anyPost('/api/auth/sms/send', {
      phone: phoneVerifyForm.phone
    })

    if (response.success) {
      message.success('验证码已发送')
      // 开始倒计时
      phoneCountdown.value = 60
      const timer = setInterval(() => {
        phoneCountdown.value--
        if (phoneCountdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      message.error(response.message || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    message.error('发送验证码失败，请稍后重试')
  } finally {
    phoneCodeSending.value = false
  }
}

// 发送邮箱验证码
const sendEmailCode = async () => {
  if (!emailVerifyForm.email) {
    message.error('请先输入邮箱')
    return
  }

  if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(emailVerifyForm.email)) {
    message.error('请输入正确的邮箱格式')
    return
  }

  try {
    emailCodeSending.value = true

    const response = await anyPost('/api/auth/email/send', {
      email: emailVerifyForm.email
    })

    if (response.success) {
      message.success('验证码已发送')
      // 开始倒计时
      emailCountdown.value = 60
      const timer = setInterval(() => {
        emailCountdown.value--
        if (emailCountdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      message.error(response.message || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    message.error('发送验证码失败，请稍后重试')
  } finally {
    emailCodeSending.value = false
  }
}

// 处理手机号认证
const handlePhoneVerify = async () => {
  if (!phoneVerifyForm.phone || !phoneVerifyForm.code) {
    message.error('请填写完整信息')
    return
  }

  try {
    phoneVerifyLoading.value = true

    const response = await anyPost('/api/auth/verify/phone', {
      phone: phoneVerifyForm.phone,
      code: phoneVerifyForm.code
    })

    if (response.success) {
      message.success('手机号认证成功')
      // 更新本地用户信息
      await userStore.fetchUserInfo()
      showPhoneVerifyModal.value = false
      // 清空表单
      phoneVerifyForm.phone = ''
      phoneVerifyForm.code = ''
    } else {
      message.error(response.message || '认证失败')
    }
  } catch (error) {
    console.error('手机号认证失败:', error)
    message.error('认证失败，请稍后重试')
  } finally {
    phoneVerifyLoading.value = false
  }
}

// 处理邮箱认证
const handleEmailVerify = async () => {
  if (!emailVerifyForm.email || !emailVerifyForm.code) {
    message.error('请填写完整信息')
    return
  }

  try {
    emailVerifyLoading.value = true

    const response = await anyPost('/api/auth/verify/email', {
      email: emailVerifyForm.email,
      code: emailVerifyForm.code
    })

    if (response.success) {
      message.success('邮箱认证成功')
      // 更新本地用户信息
      await userStore.fetchUserInfo()
      showEmailVerifyModal.value = false
      // 清空表单
      emailVerifyForm.email = ''
      emailVerifyForm.code = ''
    } else {
      message.error(response.message || '认证失败')
    }
  } catch (error) {
    console.error('邮箱认证失败:', error)
    message.error('认证失败，请稍后重试')
  } finally {
    emailVerifyLoading.value = false
  }
}

// 显示编辑弹窗时初始化表单
const showEditModalHandler = () => {
  initEditForm()
  showEditModal.value = true
}

// 组件挂载时获取用户信息
onMounted(async () => {
  if (!userStore.userInfo) {
    await userStore.fetchUserInfo()
  }
  initEditForm()

  // 初始化手机号和邮箱表单
  const info = userStore.userInfo || {}
  if (info.phone) {
    phoneVerifyForm.phone = info.phone
  }
  if (info.email) {
    emailVerifyForm.email = info.email
  }
})
</script>

<style scoped>
.ant-card {
  border-radius: 8px;
}

.ant-descriptions-item-label {
  width: 120px;
  color: #666;
}
</style>